package com.young.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.young.event.UserChangePasswordLogEvent;
import com.young.event.UserChangePasswordMessageEvent;
import com.young.event.UserLoginLogEvent;
import com.young.event.UserLoginMessageEvent;
import com.young.mapper.UserMapper;
import com.young.pojo.User;
import com.young.request.ChangePasswordRequest;
import com.young.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public User login(String username, String password) {
        LambdaQueryWrapper<User>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username)
                .eq(User::getPassword,password);
        User user = userMapper.selectOne(queryWrapper);
        if (user!=null){
            log.info("登录成功=====================");
            user.setLoginTime(new Date());
            applicationEventPublisher.publishEvent(new UserLoginLogEvent(user));
            applicationEventPublisher.publishEvent(new UserLoginMessageEvent(user));
            log.info("===========================");
        }
        return user;
    }

    @Override
    public Boolean updateUser(User user) {
        user.setUpdateTime(new Date());
        return userMapper.updateById(user)>0;
    }

    @Override
    public Boolean changePassword(ChangePasswordRequest changePasswordRequest) {
        User user = userMapper.selectById(changePasswordRequest.getUserId());
        if (user==null){
            return false;
        }
        if (changePasswordRequest.getOldPassword()==null||!user.getPassword().equals(changePasswordRequest.getOldPassword())){
            log.info("密码错误");
            return false;
        }
        if (changePasswordRequest.getNewPassword()==null){
            log.info("没有设置新密码");
            return false;
        }
        user=new User();
        user.setId(changePasswordRequest.getUserId());
        user.setPassword(changePasswordRequest.getNewPassword());
        user.setUpdateTime(new Date());
        int update = userMapper.updateById(user);
        if (update<=0){
            return false;
        }
        log.info("修改密码成功===================");
        applicationEventPublisher.publishEvent(new UserChangePasswordLogEvent(user));
        applicationEventPublisher.publishEvent(new UserChangePasswordMessageEvent(user));
        log.info("===========================");
        return true;
    }
}
